//
//  MyViewController.m
//  Indie1031
//
//  Created by Michael Jablonski on 1/18/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "MyViewController.h"
#import "AboutViewController.h"
#import "AudioStreamer.h"

@interface MyViewController()
- (NSString *)hostName;
@end

@implementation MyViewController

@synthesize loadingIndicatorView;
@synthesize playItem;
@synthesize pauseItem;
@synthesize spacerItem;
@synthesize infoItem;
@synthesize toolbar;
@synthesize aboutButton;
@synthesize metaDataLabel;
@synthesize aboutViewController;
@synthesize timer;

@synthesize remoteHostStatus;
@synthesize internetConnectionStatus;
@synthesize localWiFiConnectionStatus;

/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	metaDataLabel.text = @"";
	
	[[Reachability sharedReachability] setHostName:[self hostName]];
	[[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES];
	[self updateStatus];
	
	// Observe the kNetworkReachabilityChangedNotification. When that notification is posted, the
	// method "reachabilityChanged" will be called. 
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:@"kNetworkReachabilityChangedNotification" object:nil];
	
	NSArray *items = [NSArray arrayWithObjects: pauseItem, spacerItem, infoItem, nil];
	[toolbar setItems:items animated:NO];	
	
	[self startStream:nil];
	[super viewDidLoad];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)metaDataUpdated:(NSString *)metaData
{
	// for now just hack the metadata so it looks ok.
	NSString *tmp = [metaData stringByReplacingOccurrencesOfString:@"StreamTitle='" withString:@""];
	NSString *tmp2 = [tmp stringByReplacingOccurrencesOfString:@"';" withString:@""];
	metaDataLabel.text = tmp2;
}

- (void)streamError 
{
	NSLog(@"Stream Error");
	metaDataLabel.text = @"";
	
	// We can try to reconnect...
	[loadingIndicatorView startAnimating];
	timer = [NSTimer scheduledTimerWithTimeInterval: 3.0
											 target: self
										   selector: @selector(reconnectStream)
										   userInfo: nil
											repeats: YES];	
}

- (void)reconnectStream
{
	if ([self verifyConnection])
	{
		[timer invalidate];
		timer = nil;
		[loadingIndicatorView stopAnimating];
		NSLog(@"Restarting the stream...");
		[self startStream:nil];
	}
	else
	{
		NSLog(@"Connection is not available, sleep 3 seconds.");
	}
}

- (void)reachabilityChanged:(NSNotification *)note
{
	[self updateStatus];
	
	NSLog(@"rechabilityChanged");
}

- (void)updateStatus
{
	// Query the SystemConfiguration framework for the state of the device's network connections.
	self.remoteHostStatus           = [[Reachability sharedReachability] remoteHostStatus];
	self.internetConnectionStatus	= [[Reachability sharedReachability] internetConnectionStatus];
	self.localWiFiConnectionStatus	= [[Reachability sharedReachability] localWiFiConnectionStatus];
}

- (BOOL)verifyConnection
{
	if (self.internetConnectionStatus == NotReachable) {
		NSLog(@"NotReachable");
		return NO;
	}
	else if (self.internetConnectionStatus == ReachableViaCarrierDataNetwork) {
		NSLog(@"ReachableViaCarrierDataNetwork");
	}
	else if (self.internetConnectionStatus == ReachableViaWiFiNetwork) {
		NSLog(@"ReachableViaWiFiNetwork");
	}
	
	return YES;
}

- (NSString *)hostName
{
	// Don't include a scheme. 'http://' will break the reachability checking.
	// Change this value to test the reachability of a different host.
	return @"www.apple.com";
}

- (IBAction)showAbout:(id)sender {
	[self presentModalViewController:[self aboutViewController] animated:YES];
}

- (AboutViewController *)aboutViewController {
    // Instantiate the about view controller if necessary.
    if (aboutViewController == nil) {
        aboutViewController = [[AboutViewController alloc] initWithNibName:@"AboutView" bundle:nil];
    }
    return aboutViewController;
}

- (IBAction)startStream:(id)sender {
	
	if ([self verifyConnection]) {
		NSArray *items = [NSArray arrayWithObjects: pauseItem, spacerItem, infoItem, nil];
		[toolbar setItems:items animated:NO];	
		
		[self startStopStream];		
	}
	else {
		NSArray *items = [NSArray arrayWithObjects: playItem, spacerItem, infoItem, nil];
		[toolbar setItems:items animated:NO];
		
		[loadingIndicatorView stopAnimating];

		// open an alert with just an OK button
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection Error" message:@"An Internet connection could not be found. Please check your connection and try again."
													   delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
		[alert show];	
		[alert release];	
	}

}

- (IBAction)stopStream:(id)sender {
	NSArray *items = [NSArray arrayWithObjects: playItem, spacerItem, infoItem, nil];
	[toolbar setItems:items animated:NO];	
	
	[self startStopStream];
}

- (void)startStopStream {
	if (!streamer)
	{
		NSString *escapedValue =
		[(NSString *)CFURLCreateStringByAddingPercentEscapes(
															 nil,
															 (CFStringRef)@"http://208.80.52.108:80/KDLDFMCMP3",
															 NULL,
															 NULL,
															 kCFStringEncodingUTF8)
		 autorelease];
		
		NSURL *url = [NSURL URLWithString:escapedValue];
		streamer = [[AudioStreamer alloc] initWithURL:url];
		[streamer
		 addObserver:self
		 forKeyPath:@"isPlaying"
		 options:0
		 context:nil];
		
		[streamer setDelegate:self];
		[streamer setDidUpdateMetaDataSelector:@selector(metaDataUpdated:)];
		[streamer setDidErrorSelector:@selector(streamError)];
		
		[streamer start];
		
		[loadingIndicatorView startAnimating];
	}
	else
	{
		[streamer stop];
		metaDataLabel.text = @"";
		[loadingIndicatorView stopAnimating];
	}
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
						change:(NSDictionary *)change context:(void *)context
{
	if ([keyPath isEqual:@"isPlaying"])
	{
		NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
		
		if ([(AudioStreamer *)object isPlaying])
		{
			[loadingIndicatorView stopAnimating];
		}
		else
		{
			[streamer removeObserver:self forKeyPath:@"isPlaying"];
			[streamer release];
			streamer = nil;
			
			[loadingIndicatorView stopAnimating];
		}
		
		[pool release];
		return;
	}
	
	[super observeValueForKeyPath:keyPath ofObject:object change:change
						  context:context];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
	[aboutButton dealloc];
	[playItem dealloc];
	[pauseItem dealloc];
	[toolbar dealloc];
	[loadingIndicatorView dealloc];
	[super dealloc];
}


@end
